package cn.jd.order.service.impl;

import cn.jd.basic.config.BussinessException;
import cn.jd.order.domain.OrderPetAcquisition;
import cn.jd.order.domain.OrderPetAcquisitionLog;
import cn.jd.order.domain.OrderProduct;
import cn.jd.order.dto.OderPetDto;
import cn.jd.order.mapper.OrderPetAcquisitionLogMapper;
import cn.jd.order.mapper.OrderProductMapper;
import cn.jd.order.service.IOrderProductService;
import cn.jd.basic.service.impl.BasicServiceImpl;
import cn.jd.org.domain.Employee;
import cn.jd.pet.domain.SearchMasterMsg;
import cn.jd.pet.mapper.SearchMasterMsgMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jd
 * @since 2022-11-03
 */
@Service
@Transactional
public class OrderProductServiceImpl extends BasicServiceImpl<OrderProduct> implements IOrderProductService {
    @Autowired
    private OrderProductMapper orderProductMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private OrderPetAcquisitionLogMapper orderPetAcquisitionLogMapper;
    /**
     * 订单取消
     * @param id
     * @param employee
     */
    @Override
    public void cancel(Long id, Employee employee) {
        // 查询当前订单是否存在
        OrderProduct orderProduct = orderProductMapper.findById(id);
        if(orderProduct==null){
            throw  new BussinessException("当前订单不存在");
        }
        // 修改订单状态
        orderProduct.setState(-1);
        // 修改订单
        orderProductMapper.update(orderProduct);
        // 查询待处理数据是否存在
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(orderProduct.getSearchMasterMsgId());
        if(searchMasterMsg==null){
            throw  new BussinessException("当前信息不存在");
        }
        searchMasterMsg.setState(1);
        searchMasterMsg.setShopId(null);
        searchMasterMsgMapper.update(searchMasterMsg);
        OrderPetAcquisitionLog log = new OrderPetAcquisitionLog();
        log.setEmpId(employee.getId());
        log.setNote("员工取消订单");
        log.setPetId(orderProduct.getId());
        orderPetAcquisitionLogMapper.save(log);
    }

    /**
     * 订单确认
     * @param dto
     */
    @Override
    public void confirm(OderPetDto dto) {
        // 查询当前订单是否存在
        OrderProduct orderProduct = orderProductMapper.findById(dto.getId());
        if(orderProduct==null){
            throw  new BussinessException("当前订单不存在");
        }
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(orderProduct.getSearchMasterMsgId());
        if(searchMasterMsg==null){
            throw  new BussinessException("当前信息不存在");
        }
        searchMasterMsg.setState(3);
        searchMasterMsgMapper.update(searchMasterMsg);
        // 修改订单状态
        orderProduct.setState(1);
        orderProductMapper.update(orderProduct);
    }
}
